package com.xiyuan.almighty.service;

import java.util.concurrent.TimeUnit;

/**
 * @创建人 袁继鑫
 * @创建时间 2021-04-07 10:20
 * @版本 1.0
 * @描述
 */

public class Test {
    public static void main(String[] args) {

        MyStack1 stack = new MyStack1();

        new Thread(() -> {
            for (char c = 'A'; c <= 'Z'; c++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                stack.push(c + "");
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 1; i <= 26; i++) {
                stack.pop();
            }
        }, "线程B").start();

    }
}

class MyStack1 {
    String[] data = {"", "", "", "", "", ""};
    int index;

    public synchronized void push(String s) {
        while (data.length == index) {
//                System.out.println("开始等待，不再生产");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print(s + " pushed   ");
        data[index] = s;
        index++;
        print();
        this.notifyAll();//通知消费者

    }

    public synchronized void pop() {
        while (index == 0) {
            try {
//                    System.out.println("开始等待，不再消费");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        index--;
        String o = data[index];
        data[index] = "";
        System.out.print(o + " poped    ");
        print();
        this.notifyAll();
    }

    public void print() {
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i] + " ");
        }
        System.out.println();
    }
}
